package com.six.core.service.impl;



import com.alibaba.fastjson.JSON;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.profile.DefaultProfile;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.gson.Gson;
import com.six.core.entity.TbUser;
import com.six.core.mapper.UserMapper;
import com.six.core.service.UserService;
import com.six.core.util.JwtUtil;
import com.six.core.util.WebUtil;
import com.six.core.vo.RegVo;
import com.six.core.vo.Result;
import com.six.core.vo.TbUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.*;

import java.util.List;

/**
 * @Description:
 * @author:LiWei
 * @date:2023年02月28日9:48
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, TbUser> implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    @Override
    public Result findAll(Integer currentPage, Integer pageSize, TbUserVo tbUserVo) {
        Page<TbUser> page = new Page<>(currentPage, pageSize);
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.like(tbUserVo.getMobile()!=null&&tbUserVo.getMobile()!="" ,"mobile",tbUserVo.getMobile());
        wrapper.like(tbUserVo.getNickname()!=null&&tbUserVo.getNickname()!="" ,"nickname",tbUserVo.getNickname());
        wrapper.ge(tbUserVo.getGmtCreate()!=null&&tbUserVo.getGmtCreate()!="" ,"gmt_create",tbUserVo.getGmtCreate());
        wrapper.le(tbUserVo.getGmtCreate()!=null&&tbUserVo.getGmtModified()!="" ,"gmt_create",tbUserVo.getGmtCreate());
        wrapper.like(tbUserVo.getIsDisabled()!=null ,"is_disabled",tbUserVo.getIsDisabled());
        Page<TbUser> tbUserPage = userMapper.selectPage(page, wrapper);
        return new Result(200,"查询成功",tbUserPage);


    }

    @Override
    public Result addUser(RegVo regVo) {
        TbUser tbUser = new TbUser();
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        String password = regVo.getRepassword();
        String encode = encoder.encode(password);
        tbUser.setPassword(encode);
        tbUser.setMobile(regVo.getMobile());
        int insert = userMapper.insert(tbUser);
        if(insert>0){
            return new Result(200,"添加成功",insert);
        }else {
            return new Result(500,"添加失败",insert);
        }
    }

    @Override
    public Result updateUser(TbUser tbUser) {
        int i = userMapper.updateById(tbUser);
        if(i>0){
            return new Result(200,"修改成功",i);
        }else {
            return new Result(500,"修改失败",i);
        }
    }

    @Override
    public Result deleteById(Integer id) {
        QueryWrapper<TbUser> wrapper = new QueryWrapper<>();
        wrapper.eq("userid",id);
        int i = userMapper.delete(wrapper);
        return new Result(200,"删除成功",null);
    }

    /**
     *商家审核通过后修改用户类型为商家
     */
    @Override
    public int setUserIsType(Integer userId) {
        UpdateWrapper<TbUser> wrapper = new UpdateWrapper<>();
        wrapper.eq("userid",userId).set("is_type", 1);
        return userMapper.update(new TbUser(), wrapper);
    }

    @Override
    public Integer findByUserNum() {
        List<TbUser> list = userMapper.findByUserNum();
        return list.size();
    }

    @Override
    public TbUser findByMobile(String mobile) {
        QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile",mobile);
        return userMapper.selectOne(queryWrapper);
    }

    @Override
    public Result send(String phone) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                "LTAI5t7xQ41hXwYv5Mga85Ls",
                "hRA88mACSIv1Iop62YYXn3QU8S5UsY");


        IAcsClient client = new DefaultAcsClient(profile);
        Integer i = (int) ((Math.random() * 9 + 1) * 100000);
        String s = i.toString();

        SendSmsRequest request = new SendSmsRequest();
        request.setSignName("菜帮帮");
        request.setTemplateCode("SMS_272985217");
        request.setPhoneNumbers(phone);
        Map<String,String> map = new HashMap<>();
        map.put("code",s);
        String s1 = JSON.toJSONString(map);
        request.setTemplateParam(s1);
        System.out.println(request.getTemplateParam());
        try {
            SendSmsResponse response = client.getAcsResponse(request);
            System.out.println(new Gson().toJson(response));
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            System.out.println("ErrCode:" + e.getErrCode());
            System.out.println("ErrMsg:" + e.getErrMsg());
            System.out.println("RequestId:" + e.getRequestId());
        }
        return new Result(200,"验证码生成,成功!!!",s);
    }

    @Override
    public Result findByUserId() {
        String token = WebUtil.getRequest().getHeader("token");
        Map<String, Object> tokenChaim = JwtUtil.decodeJWT(token);
        Integer tbUserid = (Integer) tokenChaim.get("tbUserid");
        TbUser tbUser = userMapper.selectById(tbUserid);
        return new Result(200,"查询成功",tbUser);
    }

    @Override
    public Result updateUserPassword(String mobile, String newPassword) {
        // 根据手机号查询用户信息
        QueryWrapper<TbUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        TbUser tbUser = userMapper.selectOne(queryWrapper);
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        tbUser.setPassword(encoder.encode(newPassword));
        userMapper.updateById(tbUser);

        if (tbUser == null) {
            return new Result(500,"修改失败！");
        }
        return new Result(200,"密码修改成功！");
    }
}
